//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Globalization;
using System.Web;
using System.Security;
using System.Security.Permissions;

namespace Webhost
{
    /// <summary>
    /// Page hosts the silverlight plug-in
    /// </summary>
    public partial class Default : System.Web.UI.Page
    {
        /// <summary>
        /// Anonymous user name
        /// </summary>
        private const string ANONYMOUS_USER_CREDENTIALS = "NT Authority\\NETWORK SERVICE";

        /// <summary>
        /// Display name for the Anonymous user
        /// </summary>
        private const string ANONYMOUS_USER_DISPLAY_NAME = "Guest";

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        [EnvironmentPermission(SecurityAction.LinkDemand)]
        private void Page_Load(object sender, EventArgs e)
        {
            this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            agControl.InitParameters = "ClientName=workflowapplication";

            if (this.Request.IsAuthenticated)
            {
                this.tbxUserName.Value = this.User.Identity.Name;
                this.tbxDisplayName.Value = GetDisplayName(this.User.Identity.Name.Substring(this.User.Identity.Name.IndexOf("\\", StringComparison.Ordinal) + 1));
            }
            else
            {
                ////Set the system user name for anonymous mode
                this.tbxUserName.Value = ANONYMOUS_USER_CREDENTIALS;
                this.tbxDisplayName.Value = ANONYMOUS_USER_DISPLAY_NAME;
            }
        }

        /// <summary>
        /// Gets the display name.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <returns></returns>
        [EnvironmentPermission(SecurityAction.LinkDemand)]
        private static string GetDisplayName(string userName)
        {
            try
            {
                string fullName = string.Empty;
                DirectoryContext context = new DirectoryContext(DirectoryContextType.Forest);
                GlobalCatalog globalCatalog = GlobalCatalog.FindOne(context);
                using (DirectorySearcher directorySearcher = globalCatalog.GetDirectorySearcher())
                {
                    directorySearcher.Filter = String.Format(CultureInfo.CurrentCulture, "(&(objectCategory=person)(sAMAccountName={0}))", userName);
                    SearchResult searchResult = directorySearcher.FindOne();
                    fullName = searchResult.GetDirectoryEntry().Properties["displayName"].Value.ToString();
                }

                return fullName;
            }
            catch
            {
                return userName;
            }
        }
    }
}
